<?php
namespace app\api\controller\v1;

use app\api\controller\Base;
use app\api\validate\OrderPlace;
use app\api\service\Token;
use app\api\model\Order as OrderModel;
use app\api\validate\PageParam;
use app\lib\exception\PremEx;
use app\lib\exception\OrderEx;
use app\api\validate\IdMPot;
/** 
* Document
*/
class Order extends Base {
    
    protected $beforeActionList = [
        'premOnlyUser' => ['only'=>'place'],
        'premGtUser' => ['only'=>'getsummarybyuser,getdetail']
    ];

    public function place(){
        $products = input('post.');
        $uid = Token::getCacheValue(Token::getFromHttp(),'uid');
        
        (new OrderPlace())->listGoCheck($products);

        $order = OrderModel::initByProducts($products,$uid);
        $res = $order->place(); // 下订单业务逻辑
        if($res == false){
            $orderInfo = $order->getOrderInfo();
            $resData = $orderInfo['items'];
            return $this->data($resData,'缺货',403,60002);
        }else{
            return $this->data([
                'order_no' => $order->order_no,
                'order_id' => $order->id
            ]);
        }
    }

    public function getSummaryByUser($page=1,$size=10){
        (new PageParam())->goCheck();
        $uid = Token::getCacheValue(Token::getFromHttp(),'uid');
        $res = OrderModel::getListByUser($uid,$page,$size);
        return $this->data($res);
    }

    public function getDetail($id){
        $uid = Token::getCacheValue(Token::getFromHttp(),'uid');
        (new IdMPot)->goCheck();
        $detail = OrderModel::getDetail($id);
        if(empty($detail)) throw new OrderEx('订单不存在',60001);
        if($detail['user_id'] != $uid) throw new OrderEx('当前订单不属于你',60007);
        return $this->data($detail);
    }
}